<template>
  <el-dialog
    title="基本信息"
    @close="onClose"
    @opened="onOpended"
    v-model="visible"
    :disabled="type === 'detail'"
    width="800px"
    :close-on-click-modal="false"
  >
    <div class="main">
      <el-scrollbar ref="scrollRef" height="600px" :min-size="10">
        <el-form
          :disabled="type === 'detail'"
          :model="formParams"
          ref="formRef"
          :rules="rules"
          label-width="120px"
        >
          <el-form-item label="商品名称" prop="productName">
            <el-input
              v-model.trim="formParams.productName"
              placeholder="请输入，最多10字"
              maxlength="10"
              clearable
              style="width: 300px"
            />
          </el-form-item>
          <el-form-item label="售卖类型：" prop="type">
            <div style="display: flex; align-items: flex-start; flex-wrap: wrap">
              <div>选择一项</div>
              <el-radio-group style="width: 100%" v-model="formParams.type">
                <el-radio style="width: 100%" :value="1" :label="1">微信支付</el-radio>
                <el-radio style="width: 100%" :value="2" :label="2">积分兑换</el-radio>
                <el-radio style="width: 100%" :value="3" :label="3">微信支付+积分兑换</el-radio>
              </el-radio-group>
            </div>
          </el-form-item>
          <el-row :gutter="20" v-if="formParams.type">
            <el-col :span="12" v-if="formParams.type !== 2">
              <el-form-item label="" prop="price">
                微信支付&nbsp;
                <el-input-number
                  @mousewheel.native.prevent
                  style="width: 150px"
                  v-model="formParams.price"
                  :max="9999.99"
                  :min="0.01"
                  :precision="2"
                  controls-position="right"
                  placeholder=""
                />&nbsp; 元
              </el-form-item>
            </el-col>
            <el-col :span="formParams.type === 2 ? 12 : 8" v-if="formParams.type !== 1">
              <el-form-item
                label=""
                :label-width="formParams.type === 2 ? '120px' : '0px'"
                prop="integral"
              >
                积分兑换&nbsp;
                <el-input-number
                  @mousewheel.native.prevent
                  style="width: 150px"
                  v-model="formParams.integral"
                  :max="9999.99"
                  :min="1"
                  :precision="0"
                  controls-position="right"
                  placeholder=""
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="售卖库存数量" prop="inventory">
            <el-input-number
              @mousewheel.native.prevent
              style="width: 300px"
              v-model="formParams.inventory"
              :max="9999"
              :min="min"
              :precision="0"
              controls-position="right"
              placeholder=""
            />份
          </el-form-item>
          <el-form-item label="优先级" prop="sort">
            <el-input-number
              @mousewheel.native.prevent
              style="width: 300px"
              v-model="formParams.sort"
              :max="9999"
              :min="1"
              :precision="0"
              controls-position="right"
              placeholder=""
            />
            <div style="color: red; width: 100%"
              >可以重复，重复的优先等级随机排列</div
            > </el-form-item
          >\
          <el-form-item label="产品说明" prop="productInstructions">
            <el-input
              v-model="formParams.productInstructions"
              style="width: 300px"
              :autosize="{ minRows: 3, maxRows: 5 }"
              type="textarea"
              maxlength="200"
              placeholder="请输入产品说明，最多200字"
              show-word-limit
            />
          </el-form-item>
          <el-form-item label="购买说明" prop="buyInstructions">
            <el-input
              v-model="formParams.buyInstructions"
              style="width: 300px"
              :autosize="{ minRows: 3, maxRows: 5 }"
              type="textarea"
              maxlength="200"
              placeholder="请输入购买说明，最多200字"
              show-word-limit
            />
          </el-form-item>
          <el-form-item label="使用规则" prop="useRule">
            <el-input
              v-model="formParams.useRule"
              style="width: 300px"
              :autosize="{ minRows: 3, maxRows: 5 }"
              type="textarea"
              maxlength="200"
              placeholder="请输入使用规则，最多200字"
              show-word-limit
            />
          </el-form-item>
          <el-form-item label="商品图片" prop="productImg">
            <div
              ><ImageUploadByType
                v-model="formParams.productImg"
                :isShowTip="false"
                uploadType="1"
                :limit="1"
                :fileSize="10"
                :imagePx="[344, 348]"
              />请上传大小不超过10MB格式为png/jpg/jpeg的文件,图片尺寸344px*348px</div
            >
          </el-form-item>
          <el-form-item label="详情主图" prop="productHeadimg">
            <div
              ><ImageUploadByType
                v-model="formParams.productHeadimg"
                :isShowTip="false"
                uploadType="1"
                :limit="1"
                :fileSize="10"
                :imagePx="[750, 600]"
              />请上传大小不超过10MB格式为png/jpg/jpeg的文件,图片尺寸750px*600px</div
            >
          </el-form-item>
          <el-form-item label="详情长图" prop="productInfoimg">
            <div
              ><ImageUploadByType
                v-model="formParams.productInfoimg"
                :isShowTip="false"
                uploadType="1"
                :limit="1"
                :fileSize="10"
                :imagePx="[750, 750, 1000, 10000]"
                validateRange
              />请上传大小不超过10MB格式为png/jpg/jpeg的文件,图片尺寸750px*(长度1000px~10000px)</div
            >
          </el-form-item>
        </el-form>
      </el-scrollbar>
    </div>
    <template #footer v-if="type !== 'detail'">
      <el-button :loading="submit" type="primary" @click="handleAction(true)"> 保存 </el-button>
      <el-button @click="handleAction(false)">取消</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { addProductApi, getProductDetailApi, updateProductApi } from '@/api/shopping'
import { formatTexarea } from '@/utils/tools'
import { ElMessage } from 'element-plus'

const emit = defineEmits(['refresh'])

const formRef = ref(null)
const submit = ref(false)

const visible = ref(false)
const type = ref('add')

const formParams = reactive({
  productName: '',
  type: null,
  price: null,
  integral: null,
  inventory: null,
  sort: null,
  productInstructions: '',
  buyInstructions: '',
  useRule: '',
  productImg: '',
  productHeadimg: '',
  productInfoimg: ''
})
const rules = ref({
  productName: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择售卖类型', trigger: 'change' }],
  price: [{ required: true, message: '请输入', trigger: 'blur' }],
  integral: [{ required: true, message: '请输入', trigger: 'blur' }],
  inventory: [{ required: true, message: '请输入售卖库存数量', trigger: 'blur' }],
  sort: [{ required: true, message: '请输入优先级', trigger: 'blur' }],
  productInstructions: [{ required: true, message: '请输入产品说明', trigger: 'blur' }],
  buyInstructions: [{ required: true, message: '请输入购买说明', trigger: 'blur' }],
  useRule: [{ required: true, message: '请输入使用规则', trigger: 'blur' }],
  productImg: [{ required: true, message: '请上传商品图片', trigger: 'change' }],
  productHeadimg: [{ required: true, message: '请上传详情主图', trigger: 'change' }],
  productInfoimg: [{ required: true, message: '请上传详情长图', trigger: 'change' }]
})
function onOpended() {
  formRef.value.clearValidate('combo')
  formRef.value.clearValidate('position')
}

const scrollRef = ref()
function onClose() {
  formRef.value.resetFields()
  Object.keys(formParams).forEach((key) => {
    formParams[key] = null
  })
  scrollRef.value?.setScrollTop(0)
  visible.value = false
}

function handleAction(confirm) {
  if (confirm) {
    formRef.value?.validate((valid) => {
      if (valid) {
        submit.value = true
        // 文本与内容转换成html标签
        const params = { ...formParams }
        params.productInstructions = formatTexarea(formParams.productInstructions)
        params.buyInstructions = formatTexarea(formParams.buyInstructions)
        params.useRule = formatTexarea(formParams.useRule)

        console.log('typeof params.type', typeof params.type)

        // 售卖类型
        params.price = params.type !== 2 ? params.price : null
        params.integral = params.type !== 1 ? params.integral : null

        // 商品图片
        params.productImg = params.productImg?.length ? params.productImg[0].url : ''
        params.productHeadimg = params.productHeadimg?.length ? params.productHeadimg[0].url : ''
        params.productInfoimg = params.productInfoimg?.length ? params.productInfoimg[0].url : ''
        if (type.value === 'add') {
          addProductApi(params)
            .then((res) => {
              submit.value = false
              visible.value = false
              emit('refresh')
              ElMessage({
                message: '新建成功',
                type: 'success'
              })
            })
            .catch((err) => {
              if (err?.code === 213) {
                ElMessage({
                  message: err?.msg,
                  type: 'error'
                })
              }
              submit.value = false
            })
        } else if (type.value === 'edit') {
          updateProductApi(params)
            .then((res) => {
              submit.value = false
              visible.value = false
              emit('refresh')
              ElMessage({
                message: '编辑成功',
                type: 'success'
              })
            })
            .catch((err) => {
              submit.value = false
            })
        }
      } else {
        ElMessage({
          message: '提交失败，请校验数据',
          type: 'error'
        })
        submit.value = false
      }
    })
  } else {
    onClose()
  }
}

const min = ref(1)
function getDetail(id) {
  getProductDetailApi(id).then((res) => {
    const detail = res?.data || {}
    Object.keys(formParams).map((i) => {
      formParams[i] = detail[i]
    })
    formParams.id = detail.id

    formParams.productImg = detail.productImg ? [{ url: detail.productImg }] : ''
    formParams.productHeadimg = detail.productHeadimg ? [{ url: detail.productHeadimg }] : ''
    formParams.productInfoimg = detail.productInfoimg ? [{ url: detail.productInfoimg }] : ''
    formParams.productInstructions = formatTexarea(formParams.productInstructions, 1)
    formParams.buyInstructions = formatTexarea(formParams.buyInstructions, 1)
    formParams.useRule = formatTexarea(formParams.useRule, 1)
    min.value = detail.soldOut || 1
  })
}
function init(val, id) {
  if (id) {
    getDetail(id)
  }
  visible.value = true
  type.value = val
}
defineExpose({
  init
})
</script>

<style lang="scss" scoped>
::v-deep .el-upload-list__item {
  transition: none !important;
}
.main {
  height: 600px;
  overflow-y: auto;
}
</style>
